<template>
  <div class="doctor-advice-select">
    <AutocompleteMulti
      v-model="innerValue"
      :placeholder="placeholder"
      :trigger-on-focus="true"
      :fetch-suggestions="querySearch"
      :delimiter="delimiter"
      :extra-delimiters="extraDelimiters"
      :selected-color="selectedColor"
      :deduplicate="deduplicate"
      :selection-mode="selectionMode"
      :toggle-selected="true"
      :multiLine="true"
      @change="onChange"
      @select="onSelect"
      :disabled="isdisabled"
    />
  </div>
  
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import stores from '@/store';
import AutocompleteMulti from '@/components/AutocompleteMulti.vue';

const props = withDefaults(defineProps<{
  modelValue?: string | number | null;
  placeholder?: string;
  // 分隔符，默认中文逗号
  delimiter?: string;
  // 额外识别为分隔符的符号
  extraDelimiters?: string[];
  // 已选项高亮颜色
  selectedColor?: string;
  // 是否去重（医嘱常需要允许重复，这里默认不去重）
  deduplicate?: boolean;
  // 选择模式：append 连续追加
  selectionMode?: 'auto' | 'append' | 'replace';
  // 是否禁用
  isdisabled?: boolean;
}>(), {
  placeholder: '医嘱事项，支持多选，用中文逗号分隔',
  delimiter: '，',
  extraDelimiters: () => [',', '， ', ', ', '、'],
  selectedColor: '#16ada4',
  deduplicate: false,
  selectionMode: 'append',
  isdisabled: false,
});

const emit = defineEmits<{
  (e: 'update:modelValue', v: string): void;
  (e: 'change', v: string): void;
  (e: 'select', item: any): void;
}>();

const innerValue = ref<string>(props.modelValue?.toString?.() ?? '');
watch(
  () => props.modelValue,
  (v) => {
    const nv = v == null ? '' : String(v);
    if (nv !== innerValue.value) innerValue.value = nv;
  }
);
watch(innerValue, (v) => emit('update:modelValue', v));

// 枚举数据：从基础数据字典获取 DOCTOR_ADVICE
const useBaseDataStore = stores.useBaseDataStore();
const doctorAdviceEnum = computed(() => {
  const list = useBaseDataStore.getDOCTORADVICEEnumData('DOCTOR_ADVICE');
  return Array.isArray(list) ? list : [];
});

const normalizeAdviceList = () => {
  return doctorAdviceEnum.value.map((it: any) => {
    const itemName = it.itemName || it.label || it.text || it.name || it.value || '';
    return { value: itemName, itemName, ...it };
  });
};

const createFilter = (query: string) => {
  const lower = (query || '').toLowerCase();
  return (row: any) => String(row.itemName || row.value || '')
    .toLowerCase()
    .includes(lower);
};

const querySearch = (queryString: string, cb: (items: any[]) => void) => {
  const source = normalizeAdviceList();
  if (!queryString) {
    cb(source.slice(0, 50));
    return;
  }
  const results = source.filter(createFilter(queryString));
  cb(results.slice(0, 50));
};

const onChange = (v: string) => emit('change', v);
const onSelect = (item: any) => emit('select', item);
</script>

<style scoped>
.doctor-advice-select {
  width: 100%;
}
</style>
